#include "log.h"
#include <QDir>
#include <QCoreApplication>
#include <QDateTime>
#include <QTextStream>
#include <QDebug>
#include <QMutex>

QMutex mutexlog;
QString QLog::m_strAppName = "SyncBase6RW"; //初始化静态成员变量m_strAppName'
QLog::QLog()
{
    QDir m_tDir = QDir::current();
    m_strSystemLogDir = QDir::currentPath();
    if (!m_tDir.exists(m_strSystemLogDir))   //日志总目录文件夹 没有就创建
        m_tDir.mkpath(m_strSystemLogDir);
}

QLog::~QLog()
{
}

QString QLog::GetNowTimeString()
{
    QDateTime m_dTime = QDateTime::currentDateTime();
    return m_dTime.toString("yyyy.MM.dd.hh:mm:ss");
}

void QLog::AddMsg(QString fl, char *pBuffer, ...)
{
    qDebug() << QString(pBuffer);
    mutexlog.lock();
    va_list marker;
    va_start(marker, pBuffer);
    char *szBuffer = new char[strlen(pBuffer) + BUFMAX];
    int nNum = 0;
    bool bOk = false;
    int nCount = 1;

    while (bOk == false)//20180227新增循环创建空间功能  防止数组越界
    {
        nNum = ::vsnprintf(szBuffer, BUFMAX * nCount, pBuffer, marker);
        if (nNum < 0 || nNum >= (BUFMAX * nCount))
        {
            if (szBuffer)
            {
                delete[]szBuffer;
                nCount++;
                szBuffer = new char[strlen(pBuffer) + BUFMAX * nCount];
                memset(szBuffer, 0, strlen(pBuffer) + BUFMAX * nCount);
            }
        }
        else
        {
            bOk = true;
        }
    }
    va_end(marker);


    QStringList strFl = fl.split(",");
    QDir m_tDir = QDir::current();
    if (m_strSystemLogDir.size() == 0) m_strSystemLogDir = QCoreApplication::applicationDirPath();
    QString strLogPath = m_strSystemLogDir + "/Log";
    if (!m_tDir.exists(strLogPath))     //日志总目录下面log文件夹 没有就创建
        m_tDir.mkpath(strLogPath);
    m_strAppLogDir = strLogPath + "/" + m_strAppName;
    if (!m_tDir.exists(m_strAppLogDir))  // 日志log文件夹下面带模块名字的文件夹 没有就创建
        m_tDir.mkpath(m_strAppLogDir);

    QString strpath("");
    GetCurLogPath(strpath);
    QFile m_tFile(m_tDir.filePath(strpath));
    if (false == m_tFile.open(QIODevice::Append | QIODevice::WriteOnly))
    {
        delete szBuffer;
        return;
    }
    QTextStream  out(&m_tFile);
    QString outStr = QString::fromLocal8Bit(szBuffer);    //char* 装QString
    out << "[" << GetNowTimeString() << "]" << outStr << " " << fl << QStringLiteral("行") << "\r\n";
    m_tFile.flush();
    m_tFile.close();
    delete szBuffer;
    mutexlog.unlock();

}

void QLog::SetAppNameLogDir(QString path)
{
    m_strAppName=path;
}

void QLog::GetCurLogPath(QString& strCurLogPath)
{
    QDateTime m_dTime = QDateTime::currentDateTime();
    QString strTimePath = m_dTime.toString("yyyyMM");
    QString strTimeName = m_dTime.toString("yyyyMMdd");
    strTimePath = m_strAppLogDir + "/" + strTimePath;
    QDir m_tDir = QDir::current();
    if (!m_tDir.exists(strTimePath))
        m_tDir.mkpath(strTimePath);
    strCurLogPath = strTimePath + "/" + m_strAppName + "_" + strTimeName + ".log";

}
